<?php

namespace App\Task;

use App\Model\Bill;
use App\Model\BillHistory;
use App\Model\Normal;
use App\Model\Order;
use App\Model\OrderHistory;

use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;

#[Crontab(rule: "0/1 * * * *", name: "PushStation", callback: "execute", memo: "定时备份订单")]
class PushStation
{
    public function execute(): void
    {
        try {
            $halfYearAgo = date('Y-m-d H:i:s', strtotime('-3 months'));
            Order::where('created_at', '<', $halfYearAgo)
                ->orderBy('id')
                ->limit(100)
                ->delete();
//                ->get()
//                ->each(function ($order) {
//                    Db::transaction(function () use ($order) {
//                        // 订单迁移（存在则跳过）
//                        OrderHistory::firstOrCreate(
//                            ['id' => $order->id],
//                            $order->toArray()
//                        );
//
//                        // 账单迁移
//                        Bill::where('target_id', $order->id)
//                            ->get()
//                            ->each(function ($bill) {
//                                BillHistory::firstOrCreate(
//                                    ['id' => $bill->id],
//                                    $bill->toArray()
//                                );
//                                $bill->delete();
//                            });
//
//                        $order->delete();
//                    });
//                });

        } catch (\Exception $e) {
            Normal::logger('迁移错误: '.$e->getMessage(), 'order-queue');
        }
    }

}
